<template>
  <div class="personal-center">
    <!-- 加载状态 -->
    <div v-if="initialLoading" class="initial-loading">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 个人中心头部 -->
    <div v-else class="personal-header">
      <div class="row align-items-center">
        <div class="col-md-8">
          <div class="profile-section">
            <div class="profile-avatar" @click="showAvatarUpload">
              <img v-if="userProfile.avatar" :src="userProfile.avatar" alt="头像" class="avatar-img">
              <span v-else>{{ avatarText }}</span>
              <div class="upload-overlay">
                <el-icon><Camera /></el-icon>
              </div>
            </div>
            <div class="profile-info">
              <h3>{{ userProfile.fullName || userProfile.username }}</h3>
              <p>{{ userProfile.email }}</p>
              <p>{{ getRoleDisplayName(userProfile.role) }}</p>
              <p>{{ userProfile.department || '未设置' }}</p>
              <div class="online-status">
                <el-icon :class="isOnline ? 'online' : 'offline'"><CircleFilled /></el-icon>
                <span>{{ isOnline ? '在线' : '离线' }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="col-md-4">
          <div class="row">
            <div class="col-6 mb-3">
              <div class="metric-card">
                <div class="metric-value">{{ dashboardData.totalTickets || 0 }}</div>
                <div class="metric-label">总工单</div>
                <div class="metric-trend" v-if="dashboardData.ticketTrend">
                  <el-icon :class="dashboardData.ticketTrend > 0 ? 'trend-up' : 'trend-down'">
                    <ArrowUp v-if="dashboardData.ticketTrend > 0" />
                    <ArrowDown v-else />
                  </el-icon>
                  <span>{{ Math.abs(dashboardData.ticketTrend) }}%</span>
                </div>
              </div>
            </div>
            <div class="col-6 mb-3">
              <div class="metric-card">
                <div class="metric-value">{{ dashboardData.unreadNotifications || 0 }}</div>
                <div class="metric-label">未读通知</div>
                <div class="notification-badge" v-if="dashboardData.unreadNotifications > 0">
                  <el-badge :value="dashboardData.unreadNotifications" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 导航标签 -->
    <div class="personal-nav">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="仪表板" name="dashboard">
          <template #label>
            <el-icon><Monitor /></el-icon>
            <span>仪表板</span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="我的工单" name="tickets">
          <template #label>
            <el-icon><Ticket /></el-icon>
            <span>我的工单</span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="个人资料" name="profile">
          <template #label>
            <el-icon><User /></el-icon>
            <span>个人资料</span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="通知中心" name="notifications">
          <template #label>
            <el-icon><Bell /></el-icon>
            <span>通知中心</span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="设置" name="settings">
          <template #label>
            <el-icon><Setting /></el-icon>
            <span>设置</span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="活动日志" name="activities">
          <template #label>
            <el-icon><Clock /></el-icon>
            <span>活动日志</span>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 内容区域 -->
    <div class="personal-content">
      <!-- 仪表板 -->
      <div v-if="activeTab === 'dashboard'" class="dashboard-content">
        <div class="row">
          <!-- 工单统计图表 -->
          <div class="col-md-8">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <el-icon><TrendCharts /></el-icon>
                  <span>工单趋势分析</span>
                </div>
              </template>
              <div class="chart-container">
                <canvas ref="ticketTrendChart"></canvas>
              </div>
            </el-card>
          </div>
          <div class="col-md-4">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <el-icon><PieChart /></el-icon>
                  <span>工单状态分布</span>
                </div>
              </template>
              <div class="chart-container">
                <canvas ref="ticketStatusChart"></canvas>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 最近活动 -->
        <el-card class="activity-card">
          <template #header>
            <div class="card-header">
              <el-icon><Clock /></el-icon>
              <span>最近活动</span>
            </div>
          </template>
          <div v-if="loading.activities" class="loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>
          <div v-else-if="recentActivities.length === 0" class="empty-state">
            <el-icon><Clock /></el-icon>
            <p>暂无最近活动</p>
          </div>
          <div v-else class="activity-list">
            <div v-for="activity in recentActivities" :key="activity.id" class="activity-item">
              <div class="activity-icon" :class="getActivityIconClass(activity.action)">
                <el-icon><component :is="getActivityIcon(activity.action)" /></el-icon>
              </div>
              <div class="activity-content">
                <div class="activity-title">{{ activity.description }}</div>
                <div class="activity-time">{{ formatDate(activity.timestamp) }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 我的工单 -->
      <div v-if="activeTab === 'tickets'" class="tickets-content">
        <el-card>
          <template #header>
            <div class="card-header">
              <el-icon><Ticket /></el-icon>
              <span>我的工单</span>
              <div class="header-actions">
                <el-button-group>
                  <el-button 
                    :type="ticketFilter === 'all' ? 'primary' : ''" 
                    @click="filterTickets('all')"
                  >
                    全部
                  </el-button>
                  <el-button 
                    :type="ticketFilter === 'created' ? 'primary' : ''" 
                    @click="filterTickets('created')"
                  >
                    我创建的
                  </el-button>
                  <el-button 
                    :type="ticketFilter === 'assigned' ? 'primary' : ''" 
                    @click="filterTickets('assigned')"
                  >
                    分配给我的
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>

          <!-- 工单筛选 -->
          <div class="filter-section">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-select v-model="ticketFilters.status" placeholder="所有状态" clearable>
                  <el-option label="待处理" value="OPEN" />
                  <el-option label="处理中" value="IN_PROGRESS" />
                  <el-option label="已解决" value="RESOLVED" />
                  <el-option label="已关闭" value="CLOSED" />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-select v-model="ticketFilters.priority" placeholder="所有优先级" clearable>
                  <el-option label="低" value="LOW" />
                  <el-option label="中" value="MEDIUM" />
                  <el-option label="高" value="HIGH" />
                  <el-option label="紧急" value="URGENT" />
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-input 
                  v-model="ticketFilters.search" 
                  placeholder="搜索工单..." 
                  @keyup.enter="searchTickets"
                >
                  <template #append>
                    <el-button @click="searchTickets">
                      <el-icon><Search /></el-icon>
                    </el-button>
                  </template>
                </el-input>
              </el-col>
              <el-col :span="4">
                <el-button type="primary" @click="searchTickets" class="w-100">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
              </el-col>
            </el-row>
          </div>

          <!-- 工单列表 -->
          <div v-if="loading.tickets" class="loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>
          <div v-else-if="tickets.length === 0" class="empty-state">
            <el-icon><Ticket /></el-icon>
            <p>暂无工单</p>
          </div>
          <div v-else class="ticket-list">
            <div v-for="ticket in tickets" :key="ticket.id" class="ticket-item">
              <div class="ticket-icon">
                <el-icon><Ticket /></el-icon>
              </div>
              <div class="ticket-content">
                <div class="ticket-title">{{ ticket.title }}</div>
                <div class="ticket-meta">
                  <el-tag :type="getStatusTagType(ticket.status)" size="small">
                    {{ getStatusDisplayName(ticket.status) }}
                  </el-tag>
                  <el-tag :type="getPriorityTagType(ticket.priority)" size="small">
                    {{ getPriorityDisplayName(ticket.priority) }}
                  </el-tag>
                  <span class="ticket-time">创建时间: {{ formatDate(ticket.createdAt) }}</span>
                </div>
              </div>
              <div class="ticket-number">
                <small>#{{ ticket.ticketNumber }}</small>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <el-pagination
            v-if="ticketPagination.total > 0"
            v-model:current-page="ticketPagination.page"
            v-model:page-size="ticketPagination.size"
            :total="ticketPagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleTicketPageSizeChange"
            @current-change="handleTicketPageChange"
            class="pagination"
          />
        </el-card>
      </div>

      <!-- 个人资料 -->
      <div v-if="activeTab === 'profile'" class="profile-content">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-card>
              <template #header>
                <div class="card-header">
                  <el-icon><User /></el-icon>
                  <span>基本信息</span>
                </div>
              </template>
              <el-form :model="profileForm" :rules="profileRules" ref="profileFormRef" label-width="80px">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="姓名" prop="fullName">
                      <el-input v-model="profileForm.fullName" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="邮箱" prop="email">
                      <el-input v-model="profileForm.email" type="email" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="电话" prop="phone">
                      <el-input v-model="profileForm.phone" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="部门" prop="department">
                      <el-input v-model="profileForm.department" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="职位" prop="position">
                      <el-input v-model="profileForm.position" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="个人简介" prop="bio">
                      <el-input v-model="profileForm.bio" type="textarea" :rows="3" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item>
                  <el-button type="primary" @click="updateProfile" :loading="loading.profile">
                    <el-icon><Check /></el-icon>
                    保存更改
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card>
              <template #header>
                <div class="card-header">
                  <el-icon><Key /></el-icon>
                  <span>修改密码</span>
                </div>
              </template>
              <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
                <el-form-item label="当前密码" prop="oldPassword">
                  <el-input v-model="passwordForm.oldPassword" type="password" show-password />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input v-model="passwordForm.newPassword" type="password" show-password />
                </el-form-item>
                <el-form-item label="确认新密码" prop="confirmPassword">
                  <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
                </el-form-item>
                <el-form-item>
                  <el-button type="warning" @click="changePassword" :loading="loading.password" class="w-100">
                    <el-icon><Key /></el-icon>
                    修改密码
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 通知中心 -->
      <div v-if="activeTab === 'notifications'" class="notifications-content">
        <el-card>
          <template #header>
            <div class="card-header">
              <el-icon><Bell /></el-icon>
              <span>通知中心</span>
              <div class="header-actions">
                <el-button @click="markAllAsRead" :loading="loading.notifications">
                  <el-icon><Check /></el-icon>
                  全部已读
                </el-button>
              </div>
            </div>
          </template>

          <div v-if="loading.notifications" class="loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>
          <div v-else-if="notifications.length === 0" class="empty-state">
            <el-icon><Bell /></el-icon>
            <p>暂无通知</p>
          </div>
          <div v-else class="notification-list">
            <div 
              v-for="notification in notifications" 
              :key="notification.id" 
              class="notification-item"
              :class="{ unread: !notification.isRead }"
              @click="markNotificationAsRead(notification.id)"
            >
              <div class="notification-icon" :class="getNotificationIconClass(notification.type)">
                <el-icon><component :is="getNotificationIcon(notification.type)" /></el-icon>
              </div>
              <div class="notification-content">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-message">{{ notification.message }}</div>
              </div>
              <div class="notification-time">
                {{ formatDate(notification.createdAt) }}
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <el-pagination
            v-if="notificationPagination.total > 0"
            v-model:current-page="notificationPagination.page"
            v-model:page-size="notificationPagination.size"
            :total="notificationPagination.total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleNotificationPageSizeChange"
            @current-change="handleNotificationPageChange"
            class="pagination"
          />
        </el-card>
      </div>

      <!-- 设置 -->
      <div v-if="activeTab === 'settings'" class="settings-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card>
              <template #header>
                <div class="card-header">
                  <el-icon><Bell /></el-icon>
                  <span>通知设置</span>
                </div>
              </template>
              <div class="setting-item">
                <div class="setting-label">
                  <h6>邮件通知</h6>
                  <small>接收邮件通知</small>
                </div>
                <el-switch v-model="settings.notifications.email" />
              </div>
              <div class="setting-item">
                <div class="setting-label">
                  <h6>短信通知</h6>
                  <small>接收短信通知</small>
                </div>
                <el-switch v-model="settings.notifications.sms" />
              </div>
              <div class="setting-item">
                <div class="setting-label">
                  <h6>推送通知</h6>
                  <small>接收推送通知</small>
                </div>
                <el-switch v-model="settings.notifications.push" />
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <template #header>
                <div class="card-header">
                  <el-icon><Palette /></el-icon>
                  <span>显示设置</span>
                </div>
              </template>
              <el-form :model="settings.display" label-width="80px">
                <el-form-item label="主题">
                  <el-select v-model="settings.display.theme">
                    <el-option label="浅色主题" value="light" />
                    <el-option label="深色主题" value="dark" />
                    <el-option label="跟随系统" value="auto" />
                  </el-select>
                </el-form-item>
                <el-form-item label="语言">
                  <el-select v-model="settings.display.language">
                    <el-option label="简体中文" value="zh-CN" />
                    <el-option label="English" value="en-US" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时区">
                  <el-select v-model="settings.display.timezone">
                    <el-option label="北京时间" value="Asia/Shanghai" />
                    <el-option label="UTC" value="UTC" />
                  </el-select>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
        </el-row>

        <el-card class="mt-3">
          <template #header>
            <div class="card-header">
              <el-icon><Setting /></el-icon>
              <span>偏好设置</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <h6 class="settings-title">仪表板设置</h6>
              <el-form :model="settings.preferences" label-width="100px">
                <el-form-item label="默认视图">
                  <el-select v-model="settings.preferences.defaultView">
                    <el-option label="工单列表" value="tickets" />
                    <el-option label="图表视图" value="chart" />
                    <el-option label="活动视图" value="activity" />
                  </el-select>
                </el-form-item>
                <el-form-item label="刷新间隔">
                  <el-input-number v-model="settings.preferences.refreshInterval" :min="10" :max="300" />
                  <span class="ml-2">秒</span>
                </el-form-item>
                <el-form-item label="显示图表">
                  <el-switch v-model="settings.preferences.showCharts" />
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="12">
              <h6 class="settings-title">工单设置</h6>
              <el-form :model="settings.preferences" label-width="100px">
                <el-form-item label="默认优先级">
                  <el-select v-model="settings.preferences.defaultPriority">
                    <el-option label="低" value="LOW" />
                    <el-option label="中" value="MEDIUM" />
                    <el-option label="高" value="HIGH" />
                    <el-option label="紧急" value="URGENT" />
                  </el-select>
                </el-form-item>
                <el-form-item label="自动分配">
                  <el-switch v-model="settings.preferences.autoAssign" />
                </el-form-item>
                <el-form-item label="更新通知">
                  <el-switch v-model="settings.preferences.notifyOnUpdate" />
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-button type="primary" @click="saveSettings" :loading="loading.settings">
            <el-icon><Check /></el-icon>
            保存设置
          </el-button>
        </el-card>
      </div>

      <!-- 活动日志 -->
      <div v-if="activeTab === 'activities'" class="activities-content">
        <el-card>
          <template #header>
            <div class="card-header">
              <el-icon><Clock /></el-icon>
              <span>活动日志</span>
              <div class="header-actions">
                <el-button-group>
                  <el-button 
                    :type="activityFilter === 'all' ? 'primary' : ''" 
                    @click="filterActivities('all')"
                  >
                    全部
                  </el-button>
                  <el-button 
                    :type="activityFilter === 'login' ? 'primary' : ''" 
                    @click="filterActivities('login')"
                  >
                    登录
                  </el-button>
                  <el-button 
                    :type="activityFilter === 'ticket' ? 'primary' : ''" 
                    @click="filterActivities('ticket')"
                  >
                    工单
                  </el-button>
                  <el-button 
                    :type="activityFilter === 'profile' ? 'primary' : ''" 
                    @click="filterActivities('profile')"
                  >
                    资料
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>

          <div v-if="loading.activities" class="loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>
          <div v-else-if="activities.length === 0" class="empty-state">
            <el-icon><Clock /></el-icon>
            <p>暂无活动记录</p>
          </div>
          <div v-else class="activity-list">
            <div v-for="activity in activities" :key="activity.id" class="activity-item">
              <div class="activity-icon" :class="getActivityIconClass(activity.action)">
                <el-icon><component :is="getActivityIcon(activity.action)" /></el-icon>
              </div>
              <div class="activity-content">
                <div class="activity-title">{{ activity.description }}</div>
                <div class="activity-time">{{ formatDate(activity.timestamp) }}</div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <el-pagination
            v-if="activityPagination.total > 0"
            v-model:current-page="activityPagination.page"
            v-model:page-size="activityPagination.size"
            :total="activityPagination.total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleActivityPageSizeChange"
            @current-change="handleActivityPageChange"
            class="pagination"
          />
        </el-card>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="avatarDialogVisible" title="上传头像" width="400px">
      <div class="text-center mb-3">
        <div class="profile-avatar mx-auto" ref="previewAvatar">
          <img v-if="avatarPreview" :src="avatarPreview" alt="预览头像" class="avatar-img">
          <span v-else>{{ avatarText }}</span>
        </div>
      </div>
      <el-upload
        ref="avatarUpload"
        :auto-upload="false"
        :show-file-list="false"
        accept="image/*"
        @change="handleAvatarChange"
      >
        <el-button type="primary">
          <el-icon><Upload /></el-icon>
          选择图片
        </el-button>
      </el-upload>
      <div class="mt-3">
        <el-alert
          title="支持 JPG、PNG 格式，建议尺寸 200x200 像素"
          type="info"
          :closable="false"
        />
      </div>
      <template #footer>
        <el-button @click="avatarDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="uploadAvatar" :loading="loading.avatar">上传</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, nextTick, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '../store/auth'
import { personalCenterService } from '../services/personalCenterService'
import Chart from 'chart.js/auto'
import { debounce } from 'lodash-es'
import { 
  ArrowUp, ArrowDown, Right, Back, Plus, Edit, User, Key, 
  Check, Setting, InfoFilled, Bell, UserFilled, Circle
} from '@element-plus/icons-vue'

export default {
  name: 'PersonalCenter',
  setup() {
    const authStore = useAuthStore()
    
    // 响应式数据
    const activeTab = ref('dashboard')
    const initialLoading = ref(true)
    const isOnline = ref(true)
    const refreshInterval = ref(null)
    const loading = reactive({
      dashboard: false,
      tickets: false,
      profile: false,
      password: false,
      notifications: false,
      settings: false,
      activities: false,
      avatar: false
    })

    // 用户资料
    const userProfile = ref({})
    const dashboardData = ref({})
    const recentActivities = ref([])

    // 工单相关
    const tickets = ref([])
    const ticketFilter = ref('all')
    const ticketFilters = reactive({
      status: '',
      priority: '',
      search: ''
    })
    const ticketPagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })

    // 通知相关
    const notifications = ref([])
    const notificationPagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })

    // 活动相关
    const activities = ref([])
    const activityFilter = ref('all')
    const activityPagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })

    // 表单数据
    const profileForm = reactive({
      fullName: '',
      email: '',
      phone: '',
      department: '',
      position: '',
      bio: ''
    })

    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    const settings = reactive({
      notifications: {
        email: true,
        sms: false,
        push: true
      },
      display: {
        theme: 'light',
        language: 'zh-CN',
        timezone: 'Asia/Shanghai'
      },
      preferences: {
        defaultView: 'tickets',
        refreshInterval: 30,
        showCharts: true,
        defaultPriority: 'MEDIUM',
        autoAssign: false,
        notifyOnUpdate: true
      }
    })

    // 头像上传
    const avatarDialogVisible = ref(false)
    const avatarPreview = ref('')
    const avatarFile = ref(null)

    // 表单验证规则
    const profileRules = {
      fullName: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ]
    }

    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    // 计算属性
    const avatarText = computed(() => {
      return userProfile.value.fullName 
        ? userProfile.value.fullName.charAt(0).toUpperCase()
        : 'U'
    })

    // 图表引用
    const ticketTrendChart = ref(null)
    const ticketStatusChart = ref(null)

    // 方法
    const loadUserProfile = async () => {
      try {
        const response = await personalCenterService.getProfile()
        if (response.success) {
          userProfile.value = response.data
          Object.assign(profileForm, response.data)
        }
      } catch (error) {
        console.error('加载用户资料失败:', error)
        ElMessage.error('加载用户资料失败')
      }
    }

    const loadDashboard = async () => {
      loading.dashboard = true
      try {
        const response = await personalCenterService.getDashboard()
        if (response.success) {
          dashboardData.value = response.data
          recentActivities.value = response.data.activities || []
        }
      } catch (error) {
        console.error('加载仪表板失败:', error)
        ElMessage.error('加载仪表板失败')
      } finally {
        loading.dashboard = false
      }
    }

    const loadMyTickets = async () => {
      loading.tickets = true
      try {
        const params = {
          page: ticketPagination.page - 1,
          size: ticketPagination.size,
          ...ticketFilters
        }
        
        const response = await personalCenterService.getMyTickets(params)
        if (response.success) {
          tickets.value = response.data.content
          ticketPagination.total = response.data.totalElements
        }
      } catch (error) {
        console.error('加载我的工单失败:', error)
        ElMessage.error('加载我的工单失败')
      } finally {
        loading.tickets = false
      }
    }

    const loadNotifications = async () => {
      loading.notifications = true
      try {
        const params = {
          page: notificationPagination.page - 1,
          size: notificationPagination.size
        }
        
        const response = await personalCenterService.getNotifications(params)
        if (response.success) {
          notifications.value = response.data.content
          notificationPagination.total = response.data.totalElements
        }
      } catch (error) {
        console.error('加载通知失败:', error)
        ElMessage.error('加载通知失败')
      } finally {
        loading.notifications = false
      }
    }

    const loadActivities = async () => {
      loading.activities = true
      try {
        const params = {
          page: activityPagination.page - 1,
          size: activityPagination.size,
          action: activityFilter.value === 'all' ? undefined : activityFilter.value
        }
        
        const response = await personalCenterService.getActivities(params)
        if (response.success) {
          activities.value = response.data.content
          activityPagination.total = response.data.totalElements
        }
      } catch (error) {
        console.error('加载活动日志失败:', error)
        ElMessage.error('加载活动日志失败')
      } finally {
        loading.activities = false
      }
    }

    const loadSettings = async () => {
      try {
        const response = await personalCenterService.getSettings()
        if (response.success) {
          Object.assign(settings, response.data)
        }
      } catch (error) {
        console.error('加载设置失败:', error)
      }
    }

    const updateProfile = async () => {
      loading.profile = true
      try {
        const response = await personalCenterService.updateProfile(profileForm)
        if (response.success) {
          ElMessage.success('个人资料更新成功')
          await loadUserProfile()
        } else {
          ElMessage.error(response.message || '更新失败')
        }
      } catch (error) {
        console.error('更新个人资料失败:', error)
        ElMessage.error('更新失败，请稍后重试')
      } finally {
        loading.profile = false
      }
    }

    const changePassword = async () => {
      loading.password = true
      try {
        const response = await personalCenterService.changePassword(passwordForm)
        if (response.success) {
          ElMessage.success('密码修改成功')
          Object.assign(passwordForm, {
            oldPassword: '',
            newPassword: '',
            confirmPassword: ''
          })
        } else {
          ElMessage.error(response.message || '密码修改失败')
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改失败，请稍后重试')
      } finally {
        loading.password = false
      }
    }

    const saveSettings = async () => {
      loading.settings = true
      try {
        const response = await personalCenterService.updateSettings(settings)
        if (response.success) {
          ElMessage.success('设置保存成功')
        } else {
          ElMessage.error(response.message || '保存失败')
        }
      } catch (error) {
        console.error('保存设置失败:', error)
        ElMessage.error('保存失败，请稍后重试')
      } finally {
        loading.settings = false
      }
    }

    const markNotificationAsRead = async (notificationId) => {
      try {
        const response = await personalCenterService.markNotificationAsRead(notificationId)
        if (response.success) {
          await loadNotifications()
          await loadDashboard() // 刷新未读数量
        }
      } catch (error) {
        console.error('标记通知失败:', error)
      }
    }

    const markAllAsRead = async () => {
      loading.notifications = true
      try {
        const response = await personalCenterService.markAllAsRead()
        if (response.success) {
          ElMessage.success('所有通知已标记为已读')
          await loadNotifications()
          await loadDashboard() // 刷新未读数量
        }
      } catch (error) {
        console.error('标记所有通知失败:', error)
        ElMessage.error('操作失败')
      } finally {
        loading.notifications = false
      }
    }

    const showAvatarUpload = () => {
      avatarDialogVisible.value = true
    }

    const handleAvatarChange = (file) => {
      avatarFile.value = file.raw
      const reader = new FileReader()
      reader.onload = (e) => {
        avatarPreview.value = e.target.result
      }
      reader.readAsDataURL(file.raw)
    }

    const uploadAvatar = async () => {
      if (!avatarFile.value) {
        ElMessage.warning('请选择头像文件')
        return
      }

      loading.avatar = true
      try {
        const response = await personalCenterService.uploadAvatar(avatarFile.value)
        if (response.success) {
          ElMessage.success('头像上传成功')
          avatarDialogVisible.value = false
          await loadUserProfile()
        } else {
          ElMessage.error(response.message || '上传失败')
        }
      } catch (error) {
        console.error('上传头像失败:', error)
        ElMessage.error('上传失败，请稍后重试')
      } finally {
        loading.avatar = false
      }
    }

    const filterTickets = (filter) => {
      ticketFilter.value = filter
      ticketPagination.page = 1
      loadMyTickets()
    }

    const filterActivities = (filter) => {
      activityFilter.value = filter
      activityPagination.page = 1
      loadActivities()
    }

    const searchTickets = () => {
      ticketPagination.page = 1
      loadMyTickets()
    }

    const handleTabChange = (tabName) => {
      switch(tabName) {
        case 'dashboard':
          loadDashboard()
          break
        case 'tickets':
          loadMyTickets()
          break
        case 'notifications':
          loadNotifications()
          break
        case 'settings':
          loadSettings()
          break
        case 'activities':
          loadActivities()
          break
      }
    }

    // 分页处理
    const handleTicketPageChange = (page) => {
      ticketPagination.page = page
      loadMyTickets()
    }

    const handleTicketPageSizeChange = (size) => {
      ticketPagination.size = size
      ticketPagination.page = 1
      loadMyTickets()
    }

    const handleNotificationPageChange = (page) => {
      notificationPagination.page = page
      loadNotifications()
    }

    const handleNotificationPageSizeChange = (size) => {
      notificationPagination.size = size
      notificationPagination.page = 1
      loadNotifications()
    }

    const handleActivityPageChange = (page) => {
      activityPagination.page = page
      loadActivities()
    }

    const handleActivityPageSizeChange = (size) => {
      activityPagination.size = size
      activityPagination.page = 1
      loadActivities()
    }

    // 初始化图表
    const initializeCharts = async () => {
      await nextTick()
      
      // 工单趋势图表
      if (ticketTrendChart.value) {
        new Chart(ticketTrendChart.value.getContext('2d'), {
          type: 'line',
          data: {
            labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
            datasets: [{
              label: '我创建的工单',
              data: [2, 3, 1, 4, 2, 1, 3],
              borderColor: 'rgb(102, 126, 234)',
              backgroundColor: 'rgba(102, 126, 234, 0.1)',
              tension: 0.1
            }, {
              label: '分配给我的工单',
              data: [1, 2, 3, 2, 1, 2, 1],
              borderColor: 'rgb(118, 75, 162)',
              backgroundColor: 'rgba(118, 75, 162, 0.1)',
              tension: 0.1
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: 'top',
              }
            },
            scales: {
              y: {
                beginAtZero: true
              }
            }
          }
        })
      }

      // 工单状态分布图表
      if (ticketStatusChart.value) {
        new Chart(ticketStatusChart.value.getContext('2d'), {
          type: 'doughnut',
          data: {
            labels: ['待处理', '处理中', '已解决', '已关闭'],
            datasets: [{
              data: [3, 2, 5, 2],
              backgroundColor: [
                '#ffc107',
                '#17a2b8',
                '#28a745',
                '#6c757d'
              ]
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: 'bottom',
              }
            }
          }
        })
      }
    }

    // 工具函数
    const getRoleDisplayName = (role) => {
      const roleNames = {
        'ADMIN': '管理员',
        'AGENT': '客服',
        'CUSTOMER': '客户',
        'SUPERVISOR': '主管',
        'READONLY': '只读用户'
      }
      return roleNames[role] || role
    }

    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString('zh-CN')
    }

    const getStatusTagType = (status) => {
      const types = {
        'OPEN': 'warning',
        'IN_PROGRESS': 'primary',
        'RESOLVED': 'success',
        'CLOSED': 'info'
      }
      return types[status] || 'info'
    }

    const getPriorityTagType = (priority) => {
      const types = {
        'LOW': 'success',
        'MEDIUM': 'primary',
        'HIGH': 'warning',
        'URGENT': 'danger'
      }
      return types[priority] || 'primary'
    }

    const getStatusDisplayName = (status) => {
      const names = {
        'OPEN': '待处理',
        'IN_PROGRESS': '处理中',
        'RESOLVED': '已解决',
        'CLOSED': '已关闭'
      }
      return names[status] || status
    }

    const getPriorityDisplayName = (priority) => {
      const names = {
        'LOW': '低',
        'MEDIUM': '中',
        'HIGH': '高',
        'URGENT': '紧急'
      }
      return names[priority] || priority
    }

    const getNotificationIcon = (type) => {
      const icons = {
        'TICKET_CREATED': Plus,
        'TICKET_UPDATED': Edit,
        'TICKET_ASSIGNED': UserFilled,
        'TICKET_RESOLVED': Check,
        'SYSTEM': Setting,
        'INFO': InfoFilled
      }
      return icons[type] || Bell
    }

    const getNotificationIconClass = (type) => {
      const classes = {
        'TICKET_CREATED': 'bg-success',
        'TICKET_UPDATED': 'bg-primary',
        'TICKET_ASSIGNED': 'bg-warning',
        'TICKET_RESOLVED': 'bg-success',
        'SYSTEM': 'bg-secondary',
        'INFO': 'bg-info'
      }
      return classes[type] || 'bg-primary'
    }

    const getActivityIcon = (action) => {
      const icons = {
        'LOGIN': Right,
        'LOGOUT': Back,
        'TICKET_CREATED': Plus,
        'TICKET_UPDATED': Edit,
        'PROFILE_UPDATED': User,
        'PASSWORD_CHANGED': Key
      }
      return icons[action] || Circle
    }

    const getActivityIconClass = (action) => {
      const classes = {
        'LOGIN': 'bg-success',
        'LOGOUT': 'bg-secondary',
        'TICKET_CREATED': 'bg-primary',
        'TICKET_UPDATED': 'bg-warning',
        'PROFILE_UPDATED': 'bg-info',
        'PASSWORD_CHANGED': 'bg-danger'
      }
      return classes[action] || 'bg-primary'
    }

    // 防抖搜索
    const debouncedSearchTickets = debounce(searchTickets, 300)

    // 监听网络状态
    const updateOnlineStatus = () => {
      isOnline.value = navigator.onLine
    }

    // 自动刷新数据
    const startAutoRefresh = () => {
      if (refreshInterval.value) {
        clearInterval(refreshInterval.value)
      }
      
      refreshInterval.value = setInterval(() => {
        if (activeTab.value === 'dashboard') {
          loadDashboard()
        } else if (activeTab.value === 'notifications') {
          loadNotifications()
        }
      }, 30000) // 30秒刷新一次
    }

    const stopAutoRefresh = () => {
      if (refreshInterval.value) {
        clearInterval(refreshInterval.value)
        refreshInterval.value = null
      }
    }

    // 监听标签页变化
    watch(activeTab, (newTab) => {
      stopAutoRefresh()
      if (newTab === 'dashboard' || newTab === 'notifications') {
        startAutoRefresh()
      }
    })

    // 生命周期
    onMounted(async () => {
      try {
        // 并行加载初始数据
        const [profileResult, dashboardResult] = await Promise.allSettled([
          loadUserProfile(),
          loadDashboard()
        ])

        // 初始化图表
        await nextTick()
        await initializeCharts()

        // 启动自动刷新
        startAutoRefresh()

        // 监听网络状态
        window.addEventListener('online', updateOnlineStatus)
        window.addEventListener('offline', updateOnlineStatus)
      } catch (error) {
        console.error('初始化个人中心失败:', error)
        ElMessage.error('初始化失败，请刷新页面重试')
      } finally {
        initialLoading.value = false
      }
    })

    onUnmounted(() => {
      stopAutoRefresh()
      window.removeEventListener('online', updateOnlineStatus)
      window.removeEventListener('offline', updateOnlineStatus)
    })

    return {
      // 响应式数据
      activeTab,
      initialLoading,
      isOnline,
      loading,
      userProfile,
      dashboardData,
      recentActivities,
      tickets,
      ticketFilter,
      ticketFilters,
      ticketPagination,
      notifications,
      notificationPagination,
      activities,
      activityFilter,
      activityPagination,
      profileForm,
      passwordForm,
      settings,
      avatarDialogVisible,
      avatarPreview,
      avatarText,
      
      // 表单验证规则
      profileRules,
      passwordRules,
      
      // 图表引用
      ticketTrendChart,
      ticketStatusChart,
      
      // 方法
      loadUserProfile,
      loadDashboard,
      loadMyTickets,
      loadNotifications,
      loadActivities,
      loadSettings,
      updateProfile,
      changePassword,
      saveSettings,
      markNotificationAsRead,
      markAllAsRead,
      showAvatarUpload,
      handleAvatarChange,
      uploadAvatar,
      filterTickets,
      filterActivities,
      searchTickets,
      handleTabChange,
      handleTicketPageChange,
      handleTicketPageSizeChange,
      handleNotificationPageChange,
      handleNotificationPageSizeChange,
      handleActivityPageChange,
      handleActivityPageSizeChange,
      
      // 工具函数
      getRoleDisplayName,
      formatDate,
      getStatusTagType,
      getPriorityTagType,
      getStatusDisplayName,
      getPriorityDisplayName,
      getNotificationIcon,
      getNotificationIconClass,
      getActivityIcon,
      getActivityIconClass
    }
  }
}
</script>

<style scoped>
.personal-center {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.personal-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 15px;
  padding: 2rem;
  margin-bottom: 2rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.profile-section {
  display: flex;
  align-items: center;
}

.profile-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  font-weight: bold;
  margin-right: 2rem;
  position: relative;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.profile-avatar:hover {
  transform: scale(1.05);
}

.profile-avatar .avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.profile-avatar .upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.profile-avatar:hover .upload-overlay {
  opacity: 1;
}

.profile-info h3 {
  margin-bottom: 0.5rem;
  color: white;
}

.profile-info p {
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 0.25rem;
}

.metric-card {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  padding: 1.5rem;
  text-align: center;
  backdrop-filter: blur(10px);
}

.metric-value {
  font-size: 2.5rem;
  font-weight: bold;
  margin-bottom: 0.5rem;
}

.metric-label {
  font-size: 0.9rem;
  opacity: 0.9;
}

.personal-nav {
  background: white;
  border-radius: 15px;
  padding: 1rem;
  margin-bottom: 2rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.personal-content {
  background: white;
  border-radius: 15px;
  padding: 2rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.header-actions {
  margin-left: auto;
}

.chart-container {
  position: relative;
  height: 300px;
  margin: 1rem 0;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 3rem;
  color: #6c757d;
}

.empty-state .el-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
  opacity: 0.5;
}

.activity-item, .ticket-item, .notification-item {
  display: flex;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #f1f3f4;
  transition: background-color 0.3s ease;
  cursor: pointer;
}

.activity-item:hover, .ticket-item:hover, .notification-item:hover {
  background-color: #f8f9fa;
}

.activity-item:last-child, .ticket-item:last-child, .notification-item:last-child {
  border-bottom: none;
}

.activity-icon, .ticket-icon, .notification-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 1rem;
  font-size: 1.2rem;
  color: white;
}

.activity-content, .ticket-content, .notification-content {
  flex: 1;
}

.activity-title, .ticket-title, .notification-title {
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.activity-time, .ticket-time, .notification-time {
  font-size: 0.8rem;
  color: #6c757d;
}

.ticket-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 0.25rem;
}

.ticket-number {
  text-align: right;
}

.notification-item.unread {
  background-color: #f8f9ff;
  border-left: 4px solid #667eea;
}

.notification-message {
  color: #6c757d;
  font-size: 0.9rem;
}

.filter-section {
  margin-bottom: 1.5rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.setting-label h6 {
  margin-bottom: 0.25rem;
  font-weight: 600;
}

.setting-label small {
  color: #6c757d;
}

.settings-title {
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 1rem;
  color: #343a40;
}

.pagination {
  margin-top: 1.5rem;
  justify-content: center;
}

.bg-success { background-color: #28a745 !important; }
.bg-primary { background-color: #007bff !important; }
.bg-warning { background-color: #ffc107 !important; }
.bg-danger { background-color: #dc3545 !important; }
.bg-info { background-color: #17a2b8 !important; }
.bg-secondary { background-color: #6c757d !important; }

@media (max-width: 768px) {
  .personal-center {
    padding: 10px;
  }
  
  .personal-header {
    padding: 1.5rem;
  }
  
  .profile-section {
    flex-direction: column;
    text-align: center;
  }
  
  .profile-avatar {
    margin-right: 0;
    margin-bottom: 1rem;
  }
}
</style>
